package com.hainatong.shiphelper.module.workermgr.fragment;


import java.util.List;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hainatong.shiphelper.MvvmLazyFragment;
import com.hainatong.shiphelper.R;
import com.hainatong.shiphelper.databinding.FragmentRecyclerviewBinding;
import com.hainatong.shiphelper.databinding.HeaderShipUserlistViewBinding;
import com.hainatong.shiphelper.module.warehouse.entity.OrgUser;
import com.hainatong.shiphelper.module.workermgr.WorkerInfoDetailActivity;
import com.hainatong.shiphelper.module.workermgr.adapter.WorkerAdapter;
import com.hainatong.shiphelper.module.workermgr.entity.WorkerBean;
import com.hainatong.shiphelper.module.workermgr.viewmodel.OrgUserViewModel;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.hainatong.shiphelper.utils.RecyclerViewHelper;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;

public class WorkerFragment extends MvvmLazyFragment<FragmentRecyclerviewBinding, OrgUserViewModel>
{
    private static String WORKER_ORG_TAG = "WorkerFragment";

    public static String SELECT_WORKER_TAG = "SelectWorker";

    private WorkerAdapter adapter;

    private HeaderShipUserlistViewBinding headerBinding;

    private OrgUser orgBean;

    private List<WorkerBean>  userLsit;

    private boolean isSelectWorker = false;

    public static WorkerFragment newInstance(String scanCode)
    {
        Bundle bundle = new Bundle();
        bundle.putString( WORKER_ORG_TAG , scanCode );
        WorkerFragment mWorkerFragment = new WorkerFragment();
        mWorkerFragment.setArguments( bundle );
        return mWorkerFragment;
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.fragment_recyclerview;
    }

    @Override
    public int getBindingVariable()
    {
        return 0;
    }

    @Override
    protected void initParameters()
    {
        Bundle args = getArguments();
        if(  args != null )
        {
            String workerOrgStr = args.getString(WORKER_ORG_TAG , "");
            if( !StringUtils.isEmpty( workerOrgStr ) )
            {
                orgBean = GsonUtil.json2Obj( workerOrgStr , OrgUser.class);
            }
        }
    }

    @Override
    protected void onRetryBtnClick()
    {
    }

    @Override
    protected void initView(View view)
    {
        headerBinding = DataBindingUtil.inflate( getLayoutInflater() , R.layout.header_ship_userlist_view, (ViewGroup) viewDataBinding.recyclerview.getParent(),false);


        adapter = new WorkerAdapter();
        RecyclerViewHelper.addLinerLayoutMgrNoDecoration( viewDataBinding.recyclerview );
        viewDataBinding.recyclerview.setAdapter(adapter);

        viewDataBinding.refreshlayout.setRefreshHeader( new ClassicsHeader(getActivity()));
        viewDataBinding.refreshlayout.setRefreshFooter( new ClassicsFooter(getActivity()));
        viewDataBinding.refreshlayout.setOnRefreshListener(refreshLayout1 -> {
            viewModel.tryRefreshUser();
        } );
        viewDataBinding.refreshlayout.setOnLoadMoreListener(refreshLayout2 ->{
            viewModel.loadMoreUser();
        } );
        adapter.addHeaderView( headerBinding.getRoot() );
        adapter.setOnItemClickListener( (adapter1, view1, position) -> {
            WorkerBean mUser = adapter.getItem( position );
            // 选择  员工
            if( isSelectWorker )
            {
                LiveEventBus.get(SELECT_WORKER_TAG ,WorkerBean.class )
                            .post( mUser );
                getActivity().finish();
            }
            else
            {
                WorkerInfoDetailActivity.startViewByParam( getActivity() , mUser );
            }
        } );
        // 搜索 用户名
        headerBinding.btnSearch.setOnClickListener( v -> {
            // 搜索
            String keyWord = headerBinding.etSearch.getText().toString().trim();
            if(ObjectUtils.isNotEmpty( keyWord ))
            {
                searchUserByName( keyWord );
            }
        } );

        // 软键盘 上的 搜索 按钮
        headerBinding.etSearch.setOnKeyListener( (v, keyCode, event) -> {
            if(keyCode == KeyEvent.KEYCODE_ENTER)
            {
                String keyWordStr = headerBinding.etSearch.getText().toString().trim();
                if(!TextUtils.isEmpty( keyWordStr ))
                {
                    KeyboardUtils.hideSoftInput( getActivity() );
                    searchUserByName( keyWordStr );
                }
                return  true;
            }
            return false;
        } );

        LiveEventBus.get(SELECT_WORKER_TAG ,Boolean.class )
                    .observeSticky(this, isSelect -> {
                        isSelectWorker = isSelect;
                    } );

    }

    @Override
    protected void lazyLoad()
    {
        //roleId = "9ae81791-48a7-11eb-97c1-0c9d921bbf6e";
        if( ObjectUtils.isNotEmpty( orgBean ) )
        {
            String orgTitle = orgBean.getLevel()+" > " +orgBean.getRoleName();
            headerBinding.tvOrgTitle.setText(orgTitle);
            viewModel.queryUserByRoleId(orgBean.getUuid(),"");
        }

        viewModel.getUserListResult().observe( this ,result -> {
            if( result.isSuccess() )
            {
                if( result.isRefresh() )
                {
                    viewDataBinding.refreshlayout.finishRefresh(true);
                    if( result.getData() != null )
                    {
                        userLsit = result.getData();
                        adapter.setList(result.getData());
                    }
                }
                else
                {
                    viewDataBinding.refreshlayout.finishLoadMore(true);
                    if( result.getData() != null )
                    {
                        adapter.addData(result.getData());
                    }
                }
            }
            else
            {
                if( result.isRefresh() )
                {
                    //刷新时 加载失败
                    ToastUtils.showShort( result.getMsg() );
                }
                else
                {
                    if( result.isLoadMoreEmpty() )
                    {
                        viewDataBinding.refreshlayout.finishLoadMoreWithNoMoreData();
                    }
                }
            }
        } );
    }

    private void searchUserByName( String keyName )
    {
        if( ObjectUtils.isNotEmpty( orgBean ))
        {
            viewModel.queryUserByRoleId( orgBean.getUuid(),keyName );
        }
    }
}
